<template>
  <el-dialog
    ref="wkDialog"
    :title="title"
    :append-to-body="true"
    :close-on-click-modal="false"
    :visible.sync="showDialog"
    width="420px"
    custom-class="examine_handle"
    @close="hiddenView"
  >
    <el-form
      ref="form"
      v-if="status == 1 && examineType == 'crm_receivables'"
      :model="form"
      label-width="100px"
      label-position="top"
    >
      <el-form-item :label="isFq ? '请上传回款截图' : '收款截图'">
        <el-upload
          action="#"
          :on-success="uploadSuccess"
          :on-remove="handleRemove"
          :http-request="selectVideo"
          multiple
          accept="image/png , image/jpg, image/jpeg, image/gif"
          :limit="9"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png/gif文件，且不超过9张
          </div>
        </el-upload>
      </el-form-item>
      <!-- <el-form-item label="分期期数" :required="isFq" v-if="isFq">
        <el-input-number v-model="form.installNum" :precision="0" :disabled="redetail&&redetail.money==0" :min="0"></el-input-number>
        <div class="el-upload__tip">付款方式为账单分期和全额贷款的必填</div>
      </el-form-item> -->
      <el-form-item label="备注">
        <el-input
          v-model="content"
          :rows="5"
          :maxlength="200"
          :placeholder="placeholder"
          type="textarea"
          resize="none"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <el-form
      ref="form"
      v-if="status == 1 && examineType == 'crm_refund'"
      :model="form"
      label-width="100px"
      label-position="top"
    >
      <el-form-item label="退款截图" :required="true" v-if="refundImg">
        <el-upload
          action="#"
          :on-success="uploadSuccess"
          :on-remove="handleRemove"
          :on-change="handleimageChange"
          :http-request="selectVideoRefund"
          multiple
          :auto-upload="false"
          accept="image/png , image/jpg, image/jpeg, image/gif"
          :limit="9"
          list-type="picture"
          ref="upload"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png/gif文件，且不超过9张
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="content"
          :rows="5"
          :maxlength="200"
          :placeholder="placeholder"
          type="textarea"
          resize="none"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <el-form
      ref="form"
      v-if="status != 1 || status==1&&examineType=='crm_contract'"
      label-width="100px"
      label-position="top"
    >
      <el-form-item :label="remarkTitle">
        <el-input
          v-model="content"
          :rows="5"
          :maxlength="200"
          :placeholder="placeholder"
          type="textarea"
          resize="none"
          show-word-limit
          style="margin-bottom:39px"
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClick('cancel')">取 消</el-button>
      <el-button type="primary" @click="handleClick('confirm')" :disabled="loading"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>
<script type="text/javascript">
import {
  crmReceivablesReadAPI,
  crmReceivablesReadReturnTypeAPI,
} from "@/api/crm/receivables";
import { crmRefundReadAPI } from "@/api/crm/refund";
import { crmExamineRecordAuditAPI } from "@/api/examine";

import ElDialogLoadingMixin from "@/mixins/ElDialogLoading";
import { adminFileDeleteByIdAPI } from "@/api/admin/file";
import { crmQueryBatchIdsByIdsAPI } from "@/api/crm/vipStudents";
import request from "@/utils/request";

export default {
  name: "ExamineHandle", // 合同审核操作
  components: {},
  mixins: [ElDialogLoadingMixin],
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    // 审核 1 审核通过 2 审核拒绝 4 已撤回
    status: {
      type: [String, Number],
      default: 1,
    },
    // 详情信息id
    id: [String, Number],
    recordId: [String, Number],
    // 审核信息 config 1 固定 0 自选
    detail: {
      type: Object,
      default: () => {
        return {};
      },
    },
    // crm_contract crm_receivables oa_examine
    examineType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      showDialog: false,
      content: "", // 输入内容

      form: {
        enclosure: "",
        installNum: 0,
        content: "",
      },
      fileList: [],
      fileListedit: [],
      isFq: false,
      batchId: null,
      redetail: null,
      refundImg: false,
    };
  },
  computed: {
    title() {
      if (this.status == 1) {
        return "审批通过";
      } else if (this.status == 2) {
        return "审批拒绝";
      } else if (this.status == 4) {
        return "撤回审批";
      }
      return "";
    },
    remarkTitle() {
      if (this.status == 1) {
        return "备注";
      } else if (this.status == 2) {
        return "拒绝原因";
      } else if (this.status == 4) {
        return "撤回原因";
      }
      return "";
    },
    placeholder() {
      // 1 审核通过 2 审核拒绝 4 已撤回
      if (this.status == 1) {
        return "请输入审批意见（选填）";
      } else if (this.status == 2) {
        return "请输入审批意见（必填）";
      } else if (this.status == 4) {
        return "请输入撤回理由（必填）";
      }
      return "";
    },
  },
  watch: {
    show: {
      handler(val) {
        this.showDialog = val;
        if (!this.showDialog) return;
        if (this.examineType == "crm_receivables") {
          this.getDetial();
        } else if (this.examineType == "crm_refund") {
          this.getDetialR();
        }
      },
      deep: true,
      immediate: true,
    },
    detail: {
      handler(val) {
        console.log(111, val);
        let m = val.examineFlowList;
        if (m.length > 0 && m[m.length - 1].examineStatus == 3) {
          this.refundImg = true;
        } else {
          this.refundImg = false;
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {},
  methods: {
    async getDetial() {
      const res = await crmReceivablesReadReturnTypeAPI({
        id: this.id,
      });
      if (res && res.data) {
        let val = res.data;
        this.redetail = res.data;
        if (this.redetail && this.redetail.money == 0) {
          this.form.installNum = 1;
        }
        this.yzRepay(val.returnType);
      }
    },
    async getDetialR() {
      const res = await crmRefundReadAPI({
        id: this.id,
      });
      if (res && res.data) {
        this.batchId = res.data.batchId;
      }
    },
    yzRepay(val) {
      if (!val) return;
      let str = val.split("|")[0];
      if (str == "现金") {
        this.isFq = false;
      } else {
        this.isFq = true;
      }
    },
    /**
     * 提交数据
     */
    submitInfo() {
      if ((this.status == 2 || this.status == 4) && !this.content) {
        this.$message.error(this.placeholder);
      } else {
        let params;
        if (this.status == 1 && this.examineType == "crm_receivables") {
          // if(this.fileList.length<1){
          //   this.$message.error('请上传截图');
          //   return;
          // }
          // else if(this.isFq && this.form.installNum<1){
          //   this.$message.error('分期期数必须大于0');
          //   return;
          // }
          // else{
          if (this.fileList.length > 0) {
            let arr = [];
            this.fileList.forEach((item) => {
              arr.push(item.batchId);
            });
            this.form.enclosure = arr.join(",");
          }

          // }
          params = {
            typeId: this.id,
            recordId: this.recordId,
            status: this.status,
            remarks: this.content,
            enclosure: this.form.enclosure,
            // installNum:this.form.installNum
          };
        } else if (this.status == 1 && this.examineType == "crm_refund") {
          if (this.fileList.length < 1 && this.refundImg) {
            this.$message.error("请上传截图");
            return;
          } else {
            let arr = [];
            this.fileList.forEach((item) => {
              arr.push(item.batchId);
            });
            this.form.enclosure = arr.join(",");
          }
          params = {
            typeId: this.id,
            recordId: this.recordId,
            status: this.status,
            remarks: this.content,
            enclosure: this.form.enclosure,
          };
          if (this.refundImg && this.$refs.upload) {
            this.$refs.upload.submit();
          }
        } else {
          params = {
            typeId: this.id,
            recordId: this.recordId,
            status: this.status,
            remarks: this.content,
          };
        }
        this.sure(params);
      }
    },
    async sure(params) {
      this.loading = true;
      crmExamineRecordAuditAPI(params).then((res)=>{
        if(res){
          this.loading = false;
          this.$message.success("操作成功");
        // 刷新待办
        if (
          this.examineType == "crm_contract" ||
          this.examineType == "crm_invoice" ||
          this.examineType == "crm_receivables"
        ) {
          this.$store.dispatch("GetMessageNum");
        }
        this.resetInfo();
        this.$bus.emit("examine-handle-bus");
        this.$emit("save", { type: this.status });
        this.hiddenView();
        }
      }).catch(()=>{
        this.loading = false;
      })
      
    },

    /**
     * 操作点击
     */
    handleClick(type) {
      if (type == "cancel") {
        this.hiddenView();
        this.resetInfo();
      } else if (type == "confirm") {
        this.submitInfo();
      }
    },

    /**
     * 关闭
     */
    hiddenView() {
      this.$emit("close");
    },

    /**
     * 重置信息
     */
    resetInfo() {
      this.content = "";
      this.form.installNum = 0;
      this.form.content = "";
      this.form.enclosure = "";
      this.fileList = [];
    },

    //删除图片
    handleRemove(file, fileList) {
      this.fileList = [...fileList];
    },
    handleimageChange(file, fileList) {
      this.fileList = [...fileList];
    },
    // 上传成功时的钩子
    uploadSuccess(res, file, fileList) {},
    selectVideo(file) {
      var param = new FormData();
      Object.keys(file).forEach((key) => {
        if (key == "file") {
          param.append(key, file[key]);
        }
      });
      this.fileRe(param);
    },
    selectVideoRefund(file, fileList) {
      var param = new FormData();
      Object.keys(file).forEach((key) => {
        if (key == "file") {
          param.append(key, file[key]);
        }
      });
      param.append("batchId", this.batchId);
      this.fileRe(param);
    },
    fileRe(param) {
      request({
        url: "adminFile/upload",
        method: "post",
        data: param,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }).then((res) => {
        this.fileList.push({
          uid: res.data.fileId,
          fileId: res.data.fileId,
          url: "http://crmfile.hanpinedu.com/" + res.data.path,
          batchId: res.data.batchId,
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-dialog__wrapper /deep/ .el-dialog__body {
  padding: 10px 25px 20px;
}

.title {
  font-size: 12px;
  padding-bottom: 8px;
  color: #666;
}
.el-upload__tip {
  margin-top: 0;
}
</style>
<style lang="scss">
.examine_handle {
  .el-dialog__header {
    padding: 25px 24px 0 23px;
  }
  .el-form-item {
    margin-bottom: 0 !important;
  }
  .el-form-item__label {
    font-size: 12px !important;
    padding-bottom: 0 !important;
  }
}
</style>
